package com.mashibing.interceptor;

import com.mashibing.internalcommon.constant.TokenConstants;
import com.mashibing.internalcommon.dto.ResponseResult;
import com.mashibing.internalcommon.dto.TokenResult;
import com.mashibing.internalcommon.util.RedisPrefixUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

import static com.mashibing.internalcommon.util.JwtUtils.checkToken;
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        boolean result = true;
        String resutltString = "";

        String headerToken = request.getHeader("Authorization");

        // 解析token
        TokenResult jwtToken = checkToken(headerToken);

        if (jwtToken == null) {
            resutltString = "token is invalid";
            result = false;
        }

        // 解析成功，与redis中的token对比校验
        if (jwtToken != null) {
            // 与redis中token对比
            String redisTokenKey = RedisPrefixUtils.generatorTokenKey(jwtToken.getPhone(), jwtToken.getIdentity(), TokenConstants.ACCESS_TOKEN_TYPE);
            String token = redisTemplate.opsForValue().get(redisTokenKey);
            if (StringUtils.isBlank(headerToken) || !headerToken.equals(token)) {
                resutltString = "token is invalid";
                result = false;
            }
        }

        if (!result) {
            PrintWriter writer = response.getWriter();
            writer.print(JSONObject.fromObject(ResponseResult.fail(resutltString)).toString());
            log.warn("请求的路径：{} 有问题: {}",request.getRequestURL(),resutltString);
        }

        return result;
    }
}
